package org.chen.config;

import org.chen.entity.*;
import org.chen.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private TtsModelMapper modelMapper;
    
    @Autowired
    private TtsVoiceMapper voiceMapper;
    
    @Autowired
    private TtsModelVoiceMapper modelVoiceMapper;
    
    @Autowired
    private TtsInstructionTemplateMapper templateMapper;

    @Autowired
    private TtsLanguageMapper languageMapper;

    @Override
    @Transactional
    public void run(String... args) {
        // 检查是否需要初始化数据
        if (isInitializationRequired()) {
            initializeVoices();
            initializeModels();
            initializeModelVoiceRelationships();
            initializeInstructionTemplates();
            initializeLanguages();
        }
    }

    private boolean isInitializationRequired() {
        // 如果没有模型数据，则需要初始化
        return modelMapper.selectCount(null) == 0;
    }

    private void initializeVoices() {
        List<TtsVoice> voices = new ArrayList<>();
        
        addVoice(voices, "alloy", "Alloy", "多用途的语音");
        addVoice(voices, "echo", "Echo", "深沉的语音");
        addVoice(voices, "fable", "Fable", "叙事性语音");
        addVoice(voices, "onyx", "Onyx", "正式的语音");
        addVoice(voices, "nova", "Nova", "友好的语音");
        addVoice(voices, "shimmer", "Shimmer", "愉快的语音");
        addVoice(voices, "ash", "Ash", "平静的语音");
        addVoice(voices, "sage", "Sage", "知性的语音");
        addVoice(voices, "coral", "Coral", "温暖的语音");
        addVoice(voices, "ballad", "Ballad", "抒情的语音");
        addVoice(voices, "verse", "Verse", "诗意的语音");
        
        for (TtsVoice voice : voices) {
            voiceMapper.insert(voice);
        }
    }

    private void addVoice(List<TtsVoice> voices, String voiceId, String name, String description) {
        TtsVoice voice = new TtsVoice();
        voice.setVoiceId(voiceId);
        voice.setName(name);
        voice.setDescription(description);
        voice.setCreateTime(new Date());
        voice.setUpdateTime(new Date());
        voices.add(voice);
    }

    private void initializeModels() {
        List<TtsModel> models = new ArrayList<>();
        
        addModel(models, "tts-1", "TTS-1", "标准质量语音合成");
        addModel(models, "tts-1-hd", "TTS-1-HD", "高清质量语音合成");
        addModel(models, "gpt-4o-audio-preview", "GPT-4o Audio", "高级多模态语音合成");
        addModel(models, "gpt-4o-mini-audio-preview", "GPT-4o Mini Audio", "轻量版多模态模型");
        addModel(models, "gpt-4o-mini-tts", "GPT-4o Mini TTS", "支持自定义语音指令");
        
        for (TtsModel model : models) {
            modelMapper.insert(model);
        }
    }

    private void addModel(List<TtsModel> models, String modelId, String name, String description) {
        TtsModel model = new TtsModel();
        model.setModelId(modelId);
        model.setName(name);
        model.setDescription(description);
        model.setCreateTime(new Date());
        model.setUpdateTime(new Date());
        models.add(model);
    }

    private void initializeModelVoiceRelationships() {
        // 定义模型和语音的关系
        Map<String, List<String>> modelVoiceMap = new HashMap<>();
        
        // 标准TTS模型支持的音色
        modelVoiceMap.put("tts-1", Arrays.asList("alloy", "echo", "fable", "onyx", "nova", "shimmer", "ash", "sage", "coral"));
        modelVoiceMap.put("tts-1-hd", Arrays.asList("alloy", "echo", "fable", "onyx", "nova", "shimmer", "ash", "sage", "coral"));
        
        // GPT-4o系列音频模型支持的音色
        modelVoiceMap.put("gpt-4o-audio-preview", Arrays.asList("alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"));
        modelVoiceMap.put("gpt-4o-mini-audio-preview", Arrays.asList("alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"));
        
        // 新的GPT-4o Mini TTS模型支持的音色
        modelVoiceMap.put("gpt-4o-mini-tts", Arrays.asList("alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"));
        
        // 插入关系数据
        for (Map.Entry<String, List<String>> entry : modelVoiceMap.entrySet()) {
            String modelId = entry.getKey();
            List<String> voiceIds = entry.getValue();
            
            for (String voiceId : voiceIds) {
                TtsModelVoice modelVoice = new TtsModelVoice();
                modelVoice.setModelId(modelId);
                modelVoice.setVoiceId(voiceId);
                modelVoice.setCreateTime(new Date());
                modelVoiceMapper.insert(modelVoice);
            }
        }
    }

    private void initializeInstructionTemplates() {
        List<TtsInstructionTemplate> templates = new ArrayList<>();
        
        addTemplate(templates, "high-energy", "高能量", 
                "Voice Affect: Energetic and animated; dynamic with variations in pitch and tone.\n" +
                "Tone: Excited and enthusiastic.\n" +
                "Pacing: Rapid delivery with purposeful pauses for dramatic effect.\n" +
                "Emotion: Intensely focused and excited.\n" +
                "Personality: Relatable and engaging.");
        
        addTemplate(templates, "professional", "专业正式", 
                "Voice Affect: Clear and measured; consistent in delivery.\n" +
                "Tone: Professional and authoritative.\n" +
                "Pacing: Steady, moderate pace with brief pauses between main points.\n" +
                "Emotion: Confident and composed.\n" +
                "Personality: Knowledgeable and trustworthy.");
        
        addTemplate(templates, "storytelling", "讲故事", 
                "Voice Affect: Warm and inviting; varied in pitch and tone to match narrative elements.\n" +
                "Tone: Engaging and immersive.\n" +
                "Pacing: Dynamic, slowing for important details and quickening during action sequences.\n" +
                "Emotion: Expressive, reflecting the emotional content of the story.\n" +
                "Personality: Captivating and imaginative.");
        
        addTemplate(templates, "calm", "冷静平和", 
                "Voice Affect: Soft and gentle; slightly lower pitch with minimal variation.\n" +
                "Tone: Soothing and peaceful.\n" +
                "Pacing: Slow and deliberate with longer pauses.\n" +
                "Emotion: Serene and tranquil.\n" +
                "Personality: Reassuring and mindful.");
        
        addTemplate(templates, "dramatic", "戏剧性", 
                "Voice Affect: Bold and intense; significant variations in pitch and volume.\n" +
                "Tone: Dramatic and compelling.\n" +
                "Pacing: Strategic - builds tension with slow delivery, then quickens for climactic moments.\n" +
                "Emotion: Passionate and intense.\n" +
                "Personality: Charismatic and captivating.");
        
        for (TtsInstructionTemplate template : templates) {
            templateMapper.insert(template);
        }
    }

    private void initializeLanguages() {
        List<TtsLanguage> languages = new ArrayList<>();

        addLanguage(languages, "vi", "越南语");
        addLanguage(languages, "id", "印尼语");
        addLanguage(languages, "ms", "马来语");
        addLanguage(languages, "th", "泰语");
        addLanguage(languages, "zh", "中文");
        addLanguage(languages, "en", "英语");
        addLanguage(languages, "de", "德语");
        addLanguage(languages, "fr", "法语");
        addLanguage(languages, "ja", "日语");

        for (TtsLanguage language : languages) {
            languageMapper.insert(language);
        }
    }

    private void addLanguage(List<TtsLanguage> languages, String code, String name) {
        TtsLanguage language = new TtsLanguage();
        language.setLanguageCode(code);
        language.setName(name);
        language.setCreateTime(new Date());
        language.setUpdateTime(new Date());
        languages.add(language);
    }


    private void addTemplate(List<TtsInstructionTemplate> templates, String templateId, String name, String content) {
        TtsInstructionTemplate template = new TtsInstructionTemplate();
        template.setTemplateId(templateId);
        template.setName(name);
        template.setTemplateContent(content);
        template.setCreateTime(new Date());
        template.setUpdateTime(new Date());
        templates.add(template);
    }
}